import React, { useState } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import {
  Card,
  Typography,
  Form,
  Select,
  Upload,
  Button,
  message,
  UploadFile,
  Radio,
  Spin,
} from 'antd';
import { UploadOutlined } from '@ant-design/icons';
import styles from './Welcome.less';
import type { RcFile } from 'antd/es/upload/interface';
import { uploadFile, askAi } from '@/services/ant-design-pro/api'; // 导入askAi接口
import { useCurrentUser } from './useCurrentUser';

const { Option } = Select;

// 添加类型定义
interface CodePreviewProps {
  children: React.ReactNode;
}

const CodePreview: React.FC<CodePreviewProps> = ({ children }) => (
  <pre className={styles.pre}>
    <code>
      <Typography.Text copyable>{children}</Typography.Text>
    </code>
  </pre>
);

interface LanguageOption {
  value: string;
  label: string;
  extensions: string[]; // 新增文件后缀名数组
}

// 模型选项类型
interface ModelOption {
  value: string;
  label: string;
}

const Welcome: React.FC = () => {
  const [form] = Form.useForm();
  // 添加类型声明
  const [fileList, setFileList] = useState<UploadFile[]>([]);
  const [loading, setLoading] = useState(false);
  // 添加状态用于存储优化后的代码内容
  const [optimizedCode, setOptimizedCode] = useState<string>('');
  // 添加状态用于显示处理中的加载状态
  const [isProcessing, setIsProcessing] = useState<boolean>(false);

  //获取当前用户信息
  const { user } = useCurrentUser();

  // 主流的编程语言选项，添加对应的文件后缀
  const languageOptions: LanguageOption[] = [
    { value: 'java', label: 'Java', extensions: ['.java'] },
    { value: 'c', label: 'C', extensions: ['.c'] },
    { value: 'cpp', label: 'C++', extensions: ['.cpp', '.cc', '.cxx', '.h', '.hpp'] },
    { value: 'python', label: 'Python', extensions: ['.py'] },
    { value: 'javascript', label: 'JavaScript', extensions: ['.js'] },
    { value: 'typescript', label: 'TypeScript', extensions: ['.ts'] },
    { value: 'go', label: 'Go', extensions: ['.go'] },
    { value: 'rust', label: 'Rust', extensions: ['.rs'] },
  ];

  // 模型选项
  const modelOptions: ModelOption[] = [
    { value: 'deepseek-v3-250324', label: 'DeepSeek-V3 (无深度思考)' },
    { value: 'doubao-1-5-thinking-pro-250415', label: 'Doubao 1.5 Thinking Pro' },
    { value: 'deepseek-r1-250528', label: 'DeepSeek-R1' },
  ];

  // 获取优化后的代码内容 - 修改为直接读取public目录
  const fetchOptimizedCode = async (url: string) => {
    try {
      // 从url中提取文件名
      const fileName = url.substring(url.lastIndexOf('/') + 1);
      // 构建public目录下的文件路径
      const publicFilePath = `/file/${fileName}`;

      // 使用fetch API读取文件
      const response = await fetch(publicFilePath);

      if (!response.ok) {
        throw new Error(`文件读取失败: ${response.statusText}`);
      }

      const codeContent = await response.text();
      return codeContent;
    } catch (error) {
      console.error('获取优化后代码失败:', error);
      message.error('获取优化后代码失败');
      return '';
    }
  };

  const handleUpload = async () => {
    setLoading(true);
    setIsProcessing(true); // 开始处理
    setOptimizedCode(''); // 清空之前的优化结果

    try {
      // 获取表单值（包括语言和模型）
      const values = await form.validateFields();

      if (fileList.length === 0) {
        message.error('请选择要上传的文件');
        setLoading(false);
        setIsProcessing(false);
        return;
      }

      // 获取当前选择的语言
      const selectedLanguage = languageOptions.find((lang) => lang.value === values.language);

      if (!selectedLanguage) {
        message.error('未选择有效的编程语言');
        setLoading(false);
        setIsProcessing(false);
        return;
      }

      // 获取上传的文件
      const file = fileList[0].originFileObj as File;
      const fileName = file.name || '';
      const fileExtension = fileName.slice(fileName.lastIndexOf('.')).toLowerCase();

      // 检查文件后缀是否符合要求
      if (!selectedLanguage.extensions.includes(fileExtension)) {
        message.error(
          `${selectedLanguage.label} 文件后缀应为: ${selectedLanguage.extensions.join(', ')}`,
        );
        setLoading(false);
        setIsProcessing(false);
        return;
      }

      // 获取选择的模型
      const selectedModel = modelOptions.find((model) => model.value === values.model);

      console.log('上传文件:', fileList);
      console.log('上传文件名:', fileName);
      console.log('选择的语言:', values.language);
      console.log('选择的模型:', values.model, selectedModel?.label);
      console.log('当前用户的账号:', user?.userAccount);

      // 1. 文件上传逻辑
      const uploadResponse = await uploadFile(file);
      if (uploadResponse.code === 0) {
        message.success('文件上传成功！');
        const sourceFileUrl = uploadResponse.data;
        console.log('文件访问URL:', sourceFileUrl);

        // 2. 调用askAi接口
        const askAiParams = {
          sourceFileUrl,
          sourceFileName: fileName,
          languageType: values.language,
          model: values.model,
          userAccount: user?.userAccount,
        };

        console.log('调用askAi接口参数:', askAiParams);

        const aiResponse = await askAi(askAiParams);

        if (aiResponse.code === 0) {
          const optimizedFileUrl = aiResponse.data;
          console.log('优化后文件URL:', optimizedFileUrl);
          message.success('代码优化成功！');

          // 3. 获取优化后的代码内容
          const codeContent = await fetchOptimizedCode(optimizedFileUrl);
          setOptimizedCode(codeContent);
        } else {
          message.error(aiResponse.message || '代码优化失败');
        }
      } else {
        message.error(uploadResponse.message || '文件上传失败');
      }
    } catch (error) {
      console.error('处理过程中出错:', error);
      message.error('处理过程中出错，请重试');
    } finally {
      setLoading(false);
      setIsProcessing(false);
    }
  };

  // 上传配置 - 添加类型声明
  const uploadProps = {
    onRemove: (file: UploadFile) => {
      const newFileList = fileList.filter((f) => f.uid !== file.uid);
      setFileList(newFileList);
      return false;
    },
    beforeUpload: (file: RcFile) => {
      // 限制文件大小 (10MB)
      const isLt10M = file.size / 1024 / 1024 < 10;
      if (!isLt10M) {
        message.error('文件大小不能超过10MB');
        return false;
      }

      // 添加到文件列表 - 转换为 UploadFile 类型
      setFileList([
        {
          uid: file.uid, // 使用 RcFile 的 uid
          name: file.name,
          size: file.size,
          type: file.type,
          originFileObj: file,
        },
      ]);
      return false; // 阻止自动上传
    },
    fileList,
    multiple: false, // 单文件上传
  };

  return (
    <PageContainer>
      <Card>
        {/* 新增的文件上传表单 */}
        <Form form={form} layout="vertical" style={{ marginBottom: 24 }}>
          {/* 语言选择表单项 */}
          <Form.Item
            label="选择代码语言"
            name="language"
            rules={[{ required: true, message: '请选择代码语言' }]}
          >
            <Select
              placeholder="请选择代码语言"
              showSearch
              optionFilterProp="children"
              // 添加安全检查和类型转换
              filterOption={(input, option) => {
                if (!option || !option.children) return false;
                return option.children.toString().toLowerCase().includes(input.toLowerCase());
              }}
            >
              {languageOptions.map((lang) => (
                <Option key={lang.value} value={lang.value}>
                  {lang.label}
                </Option>
              ))}
            </Select>
          </Form.Item>

          {/* 新增：模型选择表单项 */}
          <Form.Item
            label="选择优化模型"
            name="model"
            initialValue="deepseek-v3-250324" // 设置默认值
            rules={[{ required: true, message: '请选择优化模型' }]}
          >
            <Radio.Group optionType="button" buttonStyle="solid">
              {modelOptions.map((model) => (
                <Radio.Button key={model.value} value={model.value}>
                  {model.label}
                </Radio.Button>
              ))}
            </Radio.Group>
          </Form.Item>

          <Form.Item label="选择代码文件" required>
            <Upload {...uploadProps}>
              <Button icon={<UploadOutlined />}>选择文件</Button>
            </Upload>
            <div style={{ marginTop: 8, color: '#999', fontSize: 12 }}>
              支持 .java, .c, .cpp, .py 等代码文件，最大10MB
            </div>
          </Form.Item>

          <Form.Item>
            <Button
              type="primary"
              onClick={handleUpload}
              loading={loading}
              disabled={fileList.length === 0}
            >
              上传并分析
            </Button>
          </Form.Item>
        </Form>

        <Typography.Text
          strong
          style={{
            marginBottom: 12,
          }}
        >
          优化后的代码区
        </Typography.Text>

        <Card bordered={false} style={{ minHeight: 300 }}>
          {isProcessing ? (
            <div style={{ textAlign: 'center', padding: '40px 0' }}>
              <Spin size="large" tip="代码优化中，请稍候..." />
              <p style={{ marginTop: 16 }}>大模型正在处理您的代码，这可能需要一些时间</p>
            </div>
          ) : optimizedCode ? (
            <CodePreview>{optimizedCode}</CodePreview>
          ) : (
            <div style={{ textAlign: 'center', color: '#bfbfbf', padding: '40px 0' }}>
              优化后的代码将显示在这里
            </div>
          )}
        </Card>
      </Card>
    </PageContainer>
  );
};

export default Welcome;
